<template>
  <div class="tenantMenu_main main_container user_container">
    <div v-loading="loading" class="main_main">
      <div class="main_main_container">
        <div class="main_main_left">
          <div class="title">部门</div>
          <div class="main_main_left_top">
            <el-tree
              ref="tree"
              :data="deptData"
              node-key="id"
              :expand-on-click-node="false"
              :default-expand-all="true"
              :highlight-current="true"
              @node-click="treeNodeClick"
            />
          </div>
        </div>
        <div class="main_main_right">
          <div class="SearchBar_main main_main_search">
            <div class="main_main_search_item">
              <div class="formItem_header">
                <div class="formItem_header_operate">
                  <a class="formItem_header_operate_items" @click="add">
                    <svg-icon icon-class="新增" />
                    <div class="item_name">新增</div>
                  </a>
                </div>
              </div>
            </div>
            <div class="main_main_search_item">
              <el-input v-model="pageData.searchValue" class="search_input" placeholder="请输入姓名或手机号" clearable @keyup.enter.native="()=>{pageData.pageNum=1; getList()}" @clear="getList" />
              <el-button class="button_icon" icon="el-icon-search" @click.stop="()=>{pageData.pageNum=1; getList()}" />
            </div>
          </div>
          <div ref="table_container" style="margin-top:20px" class="table_container">
            <el-table
              ref="table"
              :data="tableData"
              stripe
              border
              :height="tableHeight"
              style="width: 99.9%"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              @sort-change="
                (column) => {
                  sortChange(column, this);
                }
              "
              @selection-change="
                (val) => {
                  selectionChange(val, this);
                }
              "
            >
              <el-table-column type="selection" width="70" align="center" />
              <Column
                v-for="(column, index) in defaultTableColumns"
                :key="index"
                :prop="column.prop"
                :is-show="column.isShow"
                :label="column.label"
                :sortable="column.sortable"
                :width="column.width"
              />
            </el-table>
          </div>

          <div class="main_bottom">
            <pagination
              :total="total"
              :page.sync="pageData.pageNum"
              :limit.sync="pageData.pageSize"
              :selected-num="selectionsAll.length"
              @pagination="getList"
            />
          </div>
        </div>
      </div>
    </div>
    <div class="bottom_button main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">确定</el-button>
    </div>
  </div>
</template>

<script>
import {
  list,
  remove,
  updateUser,
  changeStatus,
  importMethod
} from '@/api/system/user'
import {
  treeselect as getDeptTree,
  delDept as removeDept,
  selectUserByDeptId
} from '@/api/system/dept'
import AddOrUpdate from './addOrUpdate' // 新增或编辑页面
import AddOrUpdate_Dept from '@/views/system/dept/addOrUpdate' // 新增或编辑页面

export default {
  props: {
    layerid: {},
    selectedRow: {},
    selectedIds: {}
  },
  data() {
    return {
      activeNum: 1,
      deptData: [],
      currentDeptId: '',
      currentDeptName: '',
      loading: false,
      pageId: '用户管理', // 页面唯一标识
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        isAsc: 'desc',
        searchValue: ''
      },
      total: 1, // 数据一共有多少条
      mainId: 'userId', // 表格行ID
      tableHeight: '0', // 表格高度
      tableData: [], // 表格数据
      tableColumns: [], // 表格实际用的字段
      searchColumns: [], // 搜索区实际用的字段
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      peopleList: [],
      defaultTableColumns: [
        // 表格常规字段（初始值）
        { prop: 'realName', label: '姓名' },
        { prop: 'phonenumber', label: '手机号' },
        { prop: 'email', label: '邮箱' },
        { prop: 'deptName', label: '部门' }
      ],
      defaultSearchColumns: [
        // 搜索区常规字段（初始值）
        { prop: 'realName', label: '姓名', type: 'input' },
        { prop: 'userName', label: '账号', type: 'input' }
      ],

      operationData: [
        // 右上角的操作按钮
        { label: '导入', perm: 'system:user:import' },
        { label: '新增', perm: 'system:user:add' },
        { label: '批量删除', perm: 'system:user:delete' },
        { label: '批量导出', perm: 'system:user:export' },
        { label: '页面配置', perm: '' }
      ]
    }
  },
  mounted() {
    this.getDeptTree()
    this.$nextTick(() => {
      this.tableHeight = this.$refs.table_container.offsetHeight
    })

    this.getLists()
  },
  methods: {
    getLists() {
      list(this.pageData).then(res => {
        this.peopleList = res.data
        // if (this.selectedIds) {
        //   this.selectionsAll.push(...this.selectedIds.map(item => {
        //     const data = this.peopleList.find(ele => ele.userId + '' == item)
        //     return data
        //   }))
        // }
        if (this.selectedIds) {
          const matchedData = this.peopleList.filter(ele => {
            return this.selectedIds.includes(ele.userId + '')
          })

          this.selectionsAll.push(...matchedData)
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    onSubmit() {
      this.$layer.close(this.layerid)// 关闭弹框
      this.$parent.chooseUserCallback(this.selectionsAll)
    },
    importMethod(files) {
      // 导入接口
      importMethod(files).then((res) => {
        if (res.code == 200) {
          this.$message.success('导入成功')
          this.getList()
        }
      })
    },
    deptOneClick() {
      // 默认点击一下第一级部门
      document.querySelector('.el-tree-node__content').click()
    },
    closeUser(row) {
      // 禁用
      changeStatus({ userId: row.userId, status: 0 }).then((res) => {
        this.$message({
          message: res.msg,
          type: 'success'
        })
        this.getList()
      })
    },
    getExportData(data) {
      return list(data)
    },
    openUser(row) {
      // 启用
      updateUser({ userId: row.userId, status: 1 }).then((res) => {
        this.$message({
          message: res.msg,
          type: 'success'
        })
        this.getList()
      })
    },
    unassignedUser() {
      // 未分配用户
      this.activeNum = 2
      this.currentDeptId = ''
      this.currentDeptName = '未分配用户'
      this.pageData.pageNum = 1
      this.$refs['tree'].setCurrentKey()
      Object.keys(this.pageData).forEach((key) => {
        // 给右边数据赋值
        if (
          key !== 'pageNum' &&
          key !== 'pageSize' &&
          key !== 'orderByColumn' &&
          key !== 'isAsc'
        ) {
          this.pageData[key] = ''
        }
      })
      this.getList()
    },
    disabledUser() {
      // 禁用用户
      this.activeNum = 3
      this.currentDeptId = ''
      this.currentDeptName = '禁用用户'
      this.pageData.pageNum = 1
      this.$refs['tree'].setCurrentKey()
      Object.keys(this.pageData).forEach((key) => {
        // 给右边数据赋值
        if (
          key !== 'pageNum' &&
          key !== 'pageSize' &&
          key !== 'orderByColumn' &&
          key !== 'isAsc'
        ) {
          this.pageData[key] = ''
        }
      })
      this.getList()
    },
    getDeptTree() {
      getDeptTree().then((res) => {
        this.deptData = res.data

        this.$nextTick(() => {
          this.deptOneClick()
        })
      })
    },
    getList() {
      const cachePageData = this.$deepClone(this.pageData)
      cachePageData.deptId = this.currentDeptId
      selectUserByDeptId(cachePageData).then((res) => {
        this.tableData = res.data
        this.total = res.total
        this.$nextTick(() => {
          this.setSelectRow(this) // 设置行选中
        })
      })
    },
    addNext(data) {
      // 新增下级部门
      this.$layer.iframe({
        // 弹框
        content: {
          content: AddOrUpdate_Dept, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            defaultValue: {
              parentId: data.id,
              parentName: data.label
            }
          } // props
        },
        area: ['440px', '300px'],
        title: '新增部门', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    editDept(data) {
      // 编辑部门
      this.$layer.iframe({
        // 弹框
        content: {
          content: AddOrUpdate_Dept, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            data: data
          } // props
        },
        area: ['440px', '250px'],
        title: '编辑部门', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    delDept(data) {
      // 删除部门
      const _this = this
      this.$confirm('确定要删除吗', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'cancelConfirm',
        type: 'warning'
      })
        .then(function() {
          removeDept(data.id).then((res) => {
            _this.$message({
              message: res.msg,
              type: 'success'
            })
            _this.getDeptTree()
          })
        })
        .catch(() => {})
    },
    treeNodeClick(data) {
      // 点击树节点
      this.activeNum = 1
      this.currentDeptName = data.label
      this.currentDeptId = data.id
      this.pageData.pageNum = 1
      Object.keys(this.pageData).forEach((key) => {
        // 给右边数据赋值
        if (
          key !== 'pageNum' &&
          key !== 'pageSize' &&
          key !== 'orderByColumn' &&
          key !== 'isAsc'
        ) {
          this.pageData[key] = ''
        }
      })
      this.getList()
    },
    addUserToDept(data) {
      console.log(data)
    },
    add() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: AddOrUpdate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {} // props
        },
        area: ['440px', '700px'],
        title: '新增用户', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    edit(row) {
      this.$layer.iframe({
        // 弹框
        content: {
          content: AddOrUpdate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: row[this.mainId]
          } // props
        },
        area: ['440px', '700px'],
        title: '编辑用户', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    deleteOne(row) {
      const _this = this
      this.$confirm('确定要删除吗', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'cancelConfirm',
        type: 'warning'
      })
        .then(function() {
          remove({ deleteIds: row[_this.mainId] }).then((res) => {
            _this.$message({
              message: res.msg,
              type: 'success'
            })
            _this.getList()
          })
        })
        .catch(() => {})
    },
    // 当前页的删除接口
    deleteMethod(deleteIds) {
      return remove({ deleteIds: deleteIds })
    }
  }
}
</script>

<style lang="less" scoped>
.bottom_button{
  background:white;
  height: 70px !important;
  box-shadow: 0px 0px 6px 0px rgba(29, 65, 134, 0.18);
  border-top: 1px solid rgba(29, 65, 134, 0.18);
}
.main_main {
  height: calc(100% - 70px);
}
.main_main_container {
  width: 100%;
  height: 100%;
  display: flex;

  .main_main_left {
    width: 250px;
    height: calc(100% - 70px);
    padding: 0 20px;
    .title {
      padding: 10px 0;
      border-bottom: 1px solid #387bfc;
      margin-bottom: 10px;
    }
    .main_main_left_top {
      width: 100%;
      height: calc(100% - 80px);
      overflow-y: auto;
      .el-tree {
        background-color: transparent;
      }
      /deep/ .el-tree-node__content:hover {
        background-color: rgba(56, 123, 252, 0.5) !important;
        color: white;
      }
    }
    .main_main_left_bottom {
      width: 100%;
      .main_main_left_bottom_item {
        background-color: rgba(74, 77, 82, 0.2);
        height: 40px;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding-left: 24px;
      }
      .main_main_left_bottom_item:last-child {
        border-top: 1px solid white;
      }
      .main_main_left_bottom_item:hover {
        background-color: rgba(56, 123, 252, 0.5);
        color: white;
      }
      .active {
        .main_main_left_bottom_item {
          background-color: rgba(56, 123, 252, 1);
          color: white;
        }
      }
    }
  }
  .main_main_right {
    width: calc(100% - 250px);
    height: 100%;
    display: flex;
    flex-direction: column;
    border-left: 1px solid rgba(51, 51, 51, 0.5);

  }
}
.button{
  width: 100px;
  height: 30px;
  color: #fff;
  background-color: #387bfc;
  border-radius: 4px;
  text-align: center;
  line-height: 30px;
}
.main_main{
  margin: 0 !important;
}
.formItem_header_operate_items{
  height: 30px;
  display: flex;justify-content: center;align-items: center;
  padding: 0px 10px;font-size: 16px;border-radius: 4px;
  color: rgba(56, 123, 252, 1);background-color: rgba(235, 242, 255, 1);
  .item_name{
    font-size: 14px;padding-left: 10px;
  }
}
.formItem_header_operate_items:hover{
  background-color: rgba(235, 242, 255, 0.5);
}
.table_container{
  width: 100%;
  margin-top: 20px !important;
}
.addtype-main_bottoms{
  padding-right: 20px !important;
  margin: 10px 0;
}
.main_search_item{
  padding-right: 20px !important;
}
.main_main_search{
  padding-right: 20px !important;
}
.main_main_search_item{
  padding-left: 20px !important;
}
.main_main{
  margin-right:0 !important;
  padding-top:0 !important;
}
.button_icon{
  background:#387bfc;
  width:30px;
}
.search_input{
  width:200px;
  margin-right:10px
}
</style>
